<?php
include '../../system/data/settings.php';
include '../../system/libraries/database.php';
include 'stats.inc.php';


$action = $_REQUEST['action'];

if ($action == 'get-totals')
{
print json_encode(getTotals());
}
if ($action == 'get-markets')
{
print json_encode(getMarkets());
}


function getTotals()
{
  $response = array();
  $row = array();
  
  $query = "
SELECT id, Products.name, Produse, Oferte FROM
(Select categories.name, category_id, COUNT(category_id) as Produse FROM
items INNER JOIN categories ON items.category_id = categories.id
GROUP BY category_id ) as Products
INNER JOIN
(Select shops_item_listing.status, categories.id, categories.name, count(items.id) as Oferte
FROM shops_item_listing INNER JOIN items ON shops_item_listing.item_id = items.id INNER JOIN categories ON items.category_id = categories.id   
GROUP BY  categories.id) AS Offers ON Products.category_id=Offers.id
ORDER BY Produse DESC";
   $rows = ExecuteQuery($query);
  $response['data'] = $rows;
  
  $query = "
  SELECT COUNT(categories.category_id) as Categorii, SUM(categories.Produse) as produse 
FROM

(Select categories.name, category_id, COUNT(category_id) as Produse FROM
items INNER JOIN categories ON items.category_id = categories.id
GROUP BY category_id ORDER BY produse DESC) categories  "; 
  
  
  $rows = ExecuteQuery($query);
  //$response['totals'] = $rows;
  
  $query = "SELECT COUNT(Shops.offers) as Magazine, SUM(Shops.offers) AS Oferte FROM
(SELECT COUNT(id) AS offers FROM shops INNER JOIN shops_item_listing ON shops.id = shops_item_listing.shop_id

WHERE shops.status = 1 GROUP BY shops.id ) AS Shops";
   $row = ExecuteQuery($query);
   
   
   
   
  $response['categorii'] = $rows;
  $response['magazine'] = $row;
  return $response;
}

function GetMarkets()
{
  $response = array();
  $row = array();
  $query = "Select shops_item_listing.shop_id AS Shop_ID, shops.name,  count(items.id) as Items
  FROM shops INNER JOIN shops_item_listing ON shops.id=shops_item_listing.shop_id INNER JOIN items 
  ON shops_item_listing.item_id = items.id 
  WHERE shops.status=1
  GROUP BY  Shop_ID ORDER BY Items DESC";
  
  
  $rows = ExecuteQuery($query);
  $response['data'] = $rows;
  return $response;
}

?>
